//
//  HRPictureSelectorController.swift
//  microBlog
//
//  Created by HR_W on 16/5/30.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit
import HMImagePicker

private let colCount: CGFloat = 4
private let marginP: CGFloat = 3
private let maxImageCount = 4
private let itemWidth: CGFloat = (ScreenWidth - (colCount + 1) * marginP) / colCount

private let PictureSelectorId = "PictureSelectorId"

class HRPictureSelectorController: UICollectionViewController {
    
    lazy var selectedAsset: [PHAsset] = [PHAsset]()
    //定义图片的数组
    lazy var images: [UIImage] = [UIImage]()
    override func viewDidLoad() {
        super.viewDidLoad()
       
        // Do any additional setup after loading the view.
    }
  

    init() {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(itemWidth,itemWidth)
        //设置行列的间距
        layout.minimumLineSpacing = marginP
        layout.minimumInteritemSpacing = marginP
        //设置每组的内间距
        layout.sectionInset = UIEdgeInsetsMake(marginP, marginP, 0, marginP)
        super.init(collectionViewLayout: layout)
    
        self.collectionView?.registerClass(HRPictureSelectorCell.self, forCellWithReuseIdentifier: PictureSelectorId)
        
        collectionView?.backgroundColor = UIColor.whiteColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
//数据源方法
extension HRPictureSelectorController {

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
        let delta = images.count == maxImageCount ? 0 : 1
        
        return images.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureSelectorId, forIndexPath: indexPath) as! HRPictureSelectorCell
        
        cell.backgroundColor = randomColor()
        if indexPath.item == images.count{
        
            cell.image = nil
        }else{
            cell.image = images[indexPath.item]
        }
        
        cell.selectorDelegate = self
        
        return cell
        
    }
}

extension HRPictureSelectorController: HRPictureSelectorCellDelegate{
    
    
    
    func userWillAddPicture() {
        
        print("添加图片")
        
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum){
            print("没有访问权限")
            return
        }
        let picker = HMImagePickerController(selectedAssets: selectedAsset)
        picker.pickerDelegate = self
        picker.targetSize = CGSize(width: 600, height: 600)
        picker.maxPickerCount = maxImageCount
        presentViewController(picker, animated: true, completion: nil)
        
        
//        let picker = UIImagePickerController()
//        //设置代理
//        picker.delegate = self
//        //设置图片可以被编辑
//        //picker.allowsEditing = true
//        
//        self.presentViewController(picker, animated: true, completion: nil)
//        
    }

    func userWillDeletePicture(cell: HRPictureSelectorCell) {
        print("删除图片")
        //通过点击的cell 来获取对应的indexPath
        guard let indexPath = collectionView?.indexPathForCell(cell) else {
        
            return
        }
        //删除数组中对应的数据
        images.removeAtIndex(indexPath.item)
        
        selectedAsset.removeAtIndex(indexPath.item)
        //完成后需要刷星
        collectionView?.reloadData()
        
    
    }
}

extension HRPictureSelectorController: HMImagePickerControllerDelegate{
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        self.images = images
        self.selectedAsset = selectedAssets!
        self.collectionView?.reloadData()
        self.dismissViewControllerAnimated(true, completion: nil)
    }


}

//遵守图片选择器的协议
extension HRPictureSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        print(image)
        
        print(editingInfo)
        //保存图片 添加到数组
        images.append(image)
        
        //实现协议方法之后 视图控制器的dismiss 就交给了程序猿
         self.collectionView?.reloadData()
        dismissViewControllerAnimated(true) { 
           
        }
    }
    
    
}


//定义协议
@objc protocol HRPictureSelectorCellDelegate: NSObjectProtocol
{

    optional func userWillAddPicture()
    
    optional func userWillDeletePicture(cell: HRPictureSelectorCell)

}

class HRPictureSelectorCell: UICollectionViewCell {
    
    var  image: UIImage? {
    
        didSet{
            //没有图片时 隐藏添加按钮
            deleteBtn.hidden = image == nil
            //完成给按钮设置图片
            addBtn.setImage(image, forState: .Normal)
        }
    
    }
    
    weak var selectorDelegate: HRPictureSelectorCellDelegate?
   
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc private func addBtnClick(){
        if image != nil {
            
            return
        }
    
        selectorDelegate?.userWillAddPicture?()
        
    }
    
    
    @objc private func deleteBtnClick(){
    
    selectorDelegate?.userWillDeletePicture?(self)
    
    }
    //设置界面
    private func setupUI(){
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
    
        //设置约束
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: #selector(HRPictureSelectorCell.addBtnClick), forControlEvents: .TouchUpInside)
        
        deleteBtn.addTarget(self, action: #selector(HRPictureSelectorCell.deleteBtnClick), forControlEvents: .TouchUpInside
        )
    }
    
    private lazy var addBtn: UIButton = {
    
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_pic_add"), forState: .Normal)
        btn.imageView?.contentMode = .ScaleAspectFill
        btn.imageView?.clipsToBounds = true
    
        return btn
    }()
    
    private lazy var deleteBtn: UIButton = {
    
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named:"compose_photo_close"), forState: .Normal)
        
        return btn
    }()
}
